﻿using AutoMapper;
using ProjectManageSystemApi.DbEntity;
using ProjectManageSystemApi.Enums;
using ProjectManageSystemApi.Models;
using ProjectManageSystemApi.Models.WorkerType;
using ProjectManageSystemApi.Utilities;
using System.Collections.Generic;

namespace ProjectManageSystemApi.Services.Impl
{
    public class WorkerTypeInfoServices : IWorkerTypeInfoServices
    {
        readonly IFreeSql _fsql;
        readonly IMapper _mapper;
        public WorkerTypeInfoServices(IFreeSql fsql, IMapper mapper)
        {
            _fsql = fsql;
            _mapper = mapper;
        }
        
        public bool Add(WorkerTypeInfoDto workerType) 
        {
            var data = _mapper.Map<WorkerTypeInfoDto, WorkerTypeInfo>(workerType);
            data.Status = (byte)WorkerTypeInfoStatus.Exist;
            return _fsql.Insert(data).ExecuteAffrows() > 0;
        }
        
        public bool Update(WorkerTypeInfoDto workerType) 
        {
            var data = _mapper.Map<WorkerTypeInfoDto, WorkerTypeInfo>(workerType);
            return _fsql.Update<WorkerTypeInfo>().SetSource(data).IgnoreColumns(x => new { x.Id, x.Status }).ExecuteAffrows() > 0;
        }
        
        public bool Delete(uint id) 
        {
            return _fsql.Update<WorkerTypeInfo>(id).Set(x => x.Status, (byte)WorkerTypeInfoStatus.Delete).ExecuteAffrows() > 0;
        }

        public PageVo<List<WorkerTypeInfoDto>> Query(PageBo<WorkerTypeParams> pageBo) 
        {
            var data = _fsql.Select<WorkerTypeInfo>().Where(x => x.Status == (byte)WorkerTypeInfoStatus.Exist);
            if (!pageBo.Param.Name.IsNullOrEmpty()) 
            {
                data = data.Where(x => x.Name.Contains(pageBo.Param.Name));
            }
            var total = data.Count();
            data = data.Page(pageBo.Page, pageBo.Size);
            return new PageVo<List<WorkerTypeInfoDto>>()
            {
                Page = pageBo.Page,
                Size = pageBo.Size,
                Total = total,
                Datas = _mapper.Map<List<WorkerTypeInfo>, List<WorkerTypeInfoDto>>(data.ToList())
            };
        }
        
        public bool ExistById(ulong id) 
        {
            return _fsql.Select<WorkerTypeInfo>().Any(x => x.Id == id && x.Status == (byte)WorkerTypeInfoStatus.Exist);
        }
        
        public bool ExistByName(string name, ulong id = 0) 
        {
            return _fsql.Select<WorkerTypeInfo>().Any(x => x.Id != id && x.Name == name && x.Status == (byte)WorkerTypeInfoStatus.Exist);
        }
    }
}
